<?php
/**
 * Created by PhpStorm.
 * User: admin
 * Date: 2019/1/18
 * Time: 15:33
 */

namespace app\storage\service;


use app\storage\model\MaterielModel;
use cmf\controller\AdminBaseController;
use service\k3\K3ReaderFactory;
use think\Request;

class MaterielService extends AdminBaseController
{

    private $materielModel;
    public function __construct(Request $request = null)
    {
        parent::__construct($request);
        $this->materielModel = new MaterielModel();
    }

    /**从K3上添加新物料
     * @param array $subMaterielId
     * @param bool $write
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public static function create_materiel($subMaterielId = [], $write = true)
    {
        if (empty($subMaterielId)) {
            return ret_template(true, "物料号为空");
        }

        if (is_string($subMaterielId)) {
           $temp = $subMaterielId;
            unset($subMaterielId);
            $subMaterielId[0] = $temp;
        }
        $subMaterielModel = new MaterielModel();
        $materielDb = $subMaterielModel->column('sub_materiel_id');
        $materielDiff = array_diff($subMaterielId, $materielDb);
        if (empty($materielDiff)) {
            $materielInfo  = $subMaterielModel->whereIn('sub_materiel_id',$subMaterielId)->select()->toArray();
            return ret_template(true, '数据库已经存在该物料号',$materielInfo);
        }
        $materielInfo = [];
        foreach ($materielDiff as $item) {
            $subK3 = K3ReaderFactory::read('materiel', $item);
            if (empty($subK3)) {
                return ret_template(false, "K3中不存在料号({$item})");
            }
            $materielInfo[] = $subK3[0];
        }
        foreach ($materielInfo as $k=> $item) {
            $materielInfo[$k]['uuid'] = create_uuid();
            $itemIdLen = strlen($item['item_id']);
            if($itemIdLen<6){
                $materielInfo[$k]['item_id'] = str_pad($item['item_id'],6,'0',STR_PAD_LEFT);
            }else{
                $materielInfo[$k]['item_id'] = substr($item['item_id'],1);
            }
        }
        if ($write) {
            $subMaterielModel->startTrans();
            $result = $subMaterielModel->insertAll($materielInfo);
            if ($result) {
                $subMaterielModel->commit();
                return ret_template(true, '获取成功', $materielInfo);
            } else {
                $subMaterielModel->rollback();
                return ret_template(false, '插入数据库失败');
            }
        } else {
            return ret_template(true, '获取成功', $materielInfo);
        }
    }

    public function updateMaterielInfo($materielCode = ''){
        $materielK3 = K3ReaderFactory::read('materiel', $materielCode);
        $materielList = array_column($materielK3,'sub_materiel_id');
        $materielModel = new MaterielModel();
        empty($materielCode)? $where = []:$where['sub_materiel_id'] = $materielCode;
        $materielDb = $materielModel->field('sub_materiel_id,sub_materiel_name,item_id,min_quantity')->where($where)->select();
        $materielDb = count($materielDb)? $materielDb->toArray():[];
        foreach ($materielDb as $item){
            $index = array_search($item['sub_materiel_id'],$materielList);
            if($index !== false){
                if(strlen($materielK3[$index]['item_id'])<=6){
                    $materielK3[$index]['item_id'] = str_pad($materielK3[$index]['item_id'],6,'0',STR_PAD_LEFT);
                }else{
                    $materielK3[$index]['item_id'] = substr($materielK3[$index]['item_id'],1);
                }
//                foreach ($item as $k=>$value){
//                    if($value != $materielK3[$index][$k]){
                        $materielModel->where('sub_materiel_id',$item['sub_materiel_id'])->update($materielK3[$index]);
 //                       break;
 //                   }
 //               }
            }
        }
        return ret_template(true,'更新成功');
    }
}